#!/usr/bin/env python

from distutils.core      import setup
from distutils.extension import Extension
from distutils.cmd       import Command

import os
import os.path

this_dir = os.path.dirname( os.path.abspath(__file__) )

pkg_dir  = os.path.join( this_dir, 'srp_auth' )
proto_fn = os.path.join( this_dir, 'srp_auth.proto' )
pb2_fn   = os.path.join( pkg_dir,  'srp_auth_pb2.py' )


class update_protobuf (Command):
    description = 'Regenerates the srp_auth.srp_auth_pb2 module from the protocol buffers definition file'

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        

        build_pb2 = os.path.exists( proto_fn ) and (not
                                                    os.path.exists( pb2_fn ) or
                                                    os.stat( proto_fn ).st_mtime > os.stat( pb2_fn ).st_mtime)

        if build_pb2:
            import subprocess
            import sys

            print 'Generating srp_auth.srp_auth_pb2 from protocol buffers definition...'

            try:
                p = subprocess.Popen( [ 'protoc',
                                        '-I={0}'.format( this_dir ),
                                        '--python_out={0}'.format( pkg_dir ),
                                        proto_fn ] )
        
                os.waitpid(p.pid,0)
            except OSError, e:
                if e.errno == 2:
                    print 'Unable to find the Protocol Buffers code generator.'
                    print 'Failed to update the Python protocol buffers file'
                    sys.exit(1)
        else:
            print 'The module is up to date'


ext_modules = [ Extension('srp_auth._ocrypt', ['srp_auth/_ocrypt.c',], libraries = ['ssl',]), ]

setup(name         = 'ocrypt',
	  version      = '0.1',
	  description  = 'Python Wrapper for selected OpenSSL crypto functions',
	  author       = 'Tom Cocagne',
	  author_email = 'tom.cocagne@gmail.com',
      requires     = ['srp', 'protobuf'],
      packages     = ['srp_auth'],
	  ext_modules  = ext_modules,
      cmdclass     = {'update_protobuf' : update_protobuf},)
